const http = require('http');
const url = require('url');
const fs = require('fs');
const {
  teacherInfo,
  quotaInfo,
  quotaData,
  currentUser,
  schoolYearsData,
  teachingEvaluationResult,
  collegesEvaluationResult,
} = require('./mock-data');

const requestHandler = (req, res) => {
  const path = url.parse(req.url, true);
  const { pathname } = path;
  const { method } = req;

  // 处理跨域
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader(
    'Access-Control-Allow-Headers',
    'x-requested-with,Authorization,token, content-type',
  );
  res.setHeader('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  // 对跨域下的多发的 OPTIONS 请求进行处理
  if (req.method === 'OPTIONS') {
    // CORS
    res.statusCode = 200;
    res.end();
  }

  const users = ['supervisor', 'colleges', 'teacher', 'student'];
  let currentAuthority = 'guest';

  switch (pathname) {
    case '/api/teacherInfo':
      if (method === 'GET') {
        res.write(JSON.stringify(teacherInfo));
        res.end();
      }
      break;
    case '/api/quotaInfo':
      if (method === 'GET') {
        res.write(JSON.stringify(quotaInfo));
        res.end();
      }
      break;
    case '/api/getQuotaData':
      if (method === 'GET') {
        res.write(JSON.stringify(quotaData));
        res.end();
      }
      break;
    case '/api/saveQuotaData':
      if (method === 'POST') {
        let postChunk = '';
        req.on('data', function (chunk) {
          postChunk += chunk;
        });
        req.on('end', function () {
          postChunk = JSON.parse(postChunk);
          console.log(postChunk);
          res.write(
            JSON.stringify({
              status: 'ok',
            }),
          );
          res.end();
        });
      }
      break;
    case '/api/saveTeachingEvaluationResult':
      if (method === 'POST') {
        let postChunk = '';
        req.on('data', function (chunk) {
          postChunk += chunk;
        });
        req.on('end', function () {
          postChunk = JSON.parse(postChunk);
          console.log(postChunk);
          res.write(
            JSON.stringify({
              status: 'ok',
            }),
          );
          res.end();
        });
      }
      break;
    case '/api/schoolYears':
      if (method === 'GET') {
        res.write(JSON.stringify(schoolYearsData));
        res.end();
      }
      break;
    case '/api/teacherTeachingEvaluation':
      if (method === 'GET') {
        console.log(path.query);
        res.write(JSON.stringify(teachingEvaluationResult));
        res.end();
      }
      break;
    case '/api/collegesResult':
      if (method === 'GET') {
        console.log(path.query);
        res.write(JSON.stringify(collegesEvaluationResult));
        res.end();
      }
      break;
    case '/api/login/account':
      if (method === 'POST') {
        let postChunk = '';
        req.on('data', function (chunk) {
          postChunk += chunk;
        });
        req.on('end', function () {
          postChunk = JSON.parse(postChunk);
          console.log(postChunk);

          const { userName, password } = postChunk;
          if (users.includes(userName) && password === '123456') {
            if (password === '123456' && userName === 'supervisor') {
              currentAuthority = 'supervisor';
              res.write(
                JSON.stringify({
                  status: 'ok',
                  currentAuthority: 'supervisor',
                }),
              );
            }
            if (password === '123456' && userName === 'colleges') {
              currentAuthority = 'colleges';
              res.write(
                JSON.stringify({
                  status: 'ok',
                  currentAuthority: 'colleges',
                }),
              );
            }
            if (password === '123456' && userName === 'teacher') {
              currentAuthority = 'teacher';
              res.write(
                JSON.stringify({
                  status: 'ok',
                  currentAuthority: 'teacher',
                }),
              );
            }
            if (password === '123456' && userName === 'student') {
              currentAuthority = 'student';
              res.write(
                JSON.stringify({
                  status: 'ok',
                  currentAuthority: 'student',
                }),
              );
            }
          } else {
            res.write(
              JSON.stringify({
                status: 'error',
                currentAuthority: 'guest',
              }),
            );
          }
          fs.writeFile(
            `${__dirname}/authority.json`,
            `{"currentAuthority": "${currentAuthority}"}`,
            (error) => {
              if (!error) {
                console.log('文件写入成功!');
              } else {
                console.log(error.message);
              }
            },
          );
          res.end();
        });
      }
      break;
    case '/api/currentUser':
      if (method === 'GET') {
        fs.readFile(`${__dirname}/authority.json`, (error, data) => {
          if (!error) {
            const result = JSON.parse(data);
            res.write(JSON.stringify(currentUser(result.currentAuthority)));
            res.end();
          } else {
            console.log(error);
          }
        });
      }
      break;
    default:
      break;
  }
  console.log('==>', pathname, method);
};

const dealRequest = (req, res) => {
  res.setHeader('Content-type', 'application/json');
  requestHandler(req, res);
};

const server = http.createServer(dealRequest);
server.listen(3006, 'localhost');
